using System.Diagnostics;
using System;
using System.Windows.Forms;
using System.Collections;
using System.Drawing;
using System.Data;
using System.Collections.Generic;

namespace FanTong
{
	public class UpdateMsgList
	{
		
		
		private string Url;
		private bool UseAuth;
		private int UserMsgFlg;
		private string UserName;
		private string Password;
		private string[] strFollowsIdArr;
		private string[] strFollowsImageArr;
		
		public string[] setFollowsIdArr
		{
			get
			{
				string[] returnValue;
				returnValue = strFollowsIdArr;
				return returnValue;
			}
			set
			{
				strFollowsIdArr = value;
			}
		}
		
		public string[] setFollowsImageArr
		{
			get
			{
				string[] returnValue;
				returnValue = strFollowsImageArr;
				return returnValue;
			}
			set
			{
				strFollowsImageArr = value;
			}
		}
		
		public string setURL
		{
			get
			{
				string returnValue;
				returnValue = Url;
				return returnValue;
			}
			set
			{
				Url = value;
			}
		}
		
		public bool setUseAuth
		{
			get
			{
				bool returnValue;
				returnValue = UseAuth;
				return returnValue;
			}
			set
			{
				UseAuth = value;
			}
		}
		
		public int setUserMsgFlg
		{
			get
			{
				int returnValue;
				returnValue = UserMsgFlg;
				return returnValue;
			}
			set
			{
				UserMsgFlg = value;
			}
		}
		
		public string setUserName
		{
			get
			{
				string returnValue;
				returnValue = UserName;
				return returnValue;
			}
			set
			{
				UserName = value;
			}
		}
		
		public string setPassword
		{
			get
			{
				string returnValue;
				returnValue = Password;
				return returnValue;
			}
			set
			{
				Password = value;
			}
		}
		
		public delegate void UpdateMsgListCompleteEventHandler(string innerHTML, string IDs, string[] ReplyMsgsIdArr, string[] ReplyMsgsNameArr, int[] ReplyMsgsFlagArr, string[] ReplyMsgsContentArr, string ErrorMsg);
		private UpdateMsgListCompleteEventHandler UpdateMsgListCompleteEvent;
		
		public event UpdateMsgListCompleteEventHandler UpdateMsgListComplete
		{
			add
			{
				UpdateMsgListCompleteEvent = (UpdateMsgListCompleteEventHandler) System.Delegate.Combine(UpdateMsgListCompleteEvent, value);
			}
			remove
			{
				UpdateMsgListCompleteEvent = (UpdateMsgListCompleteEventHandler) System.Delegate.Remove(UpdateMsgListCompleteEvent, value);
			}
		}
		
		
		public delegate void UpdateFriendFollowListCompleteEventHandler(string[] FriendsIdArr, string[] strFriendsArr, string[] strFollowsIdArr, string[] strFollowsNameArr, string[] strFollowsImageArr, string ErrorMsg);
		private UpdateFriendFollowListCompleteEventHandler UpdateFriendFollowListCompleteEvent;
		
		public event UpdateFriendFollowListCompleteEventHandler UpdateFriendFollowListComplete
		{
			add
			{
				UpdateFriendFollowListCompleteEvent = (UpdateFriendFollowListCompleteEventHandler) System.Delegate.Combine(UpdateFriendFollowListCompleteEvent, value);
			}
			remove
			{
				UpdateFriendFollowListCompleteEvent = (UpdateFriendFollowListCompleteEventHandler) System.Delegate.Remove(UpdateFriendFollowListCompleteEvent, value);
			}
		}
		
		
		public void UpdateFriendFollowList()
		{
			
			string ErrorMsg;
			ErrorMsg = "";
            DateTime nodate=DateTime.Now;
            //MSXML2.DOMDocumentClass xmldom = XMLMethod.sendRequest("http://api.fanfou.com/statuses/friends.xml?id=" + UserName, true, UserName, Password, ref nodate, ref ErrorMsg);
            string strxml = XMLMethod.sendRequest("http://api.fanfou.com/statuses/friends.xml?id=" + UserName, true, UserName, Password, ref nodate, ref ErrorMsg).xml;
            System.Xml.XmlDocument xmldom = new System.Xml.XmlDocument();
            xmldom.LoadXml(strxml);
            System.Xml.XmlNodeList objNodes;
            System.Xml.XmlNode node;
			string id;
			string name;
			int i;
			int count;
			
			objNodes = xmldom.SelectNodes("/users/user");
			count = objNodes.Count;
			string[] strFriendsIdArr;
			string[] strFriendsArr;
			strFriendsIdArr = new string[objNodes.Count - 1 + 1];
            strFriendsArr = new string[objNodes.Count - 1 + 1];
            for (i = 0; i <= objNodes.Count - 1; i++)
			{
                node = objNodes.Item(i);
				id = node.SelectNodes("./id")[0].InnerText;
                name = node.SelectNodes("./name")[0].InnerText;
				strFriendsIdArr[i] = id;
				strFriendsArr[i] = name;
			}

            xmldom.LoadXml(XMLMethod.sendRequest("http://api.fanfou.com/statuses/followers.xml?id=" + UserName, true, UserName, Password, ref nodate, ref ErrorMsg).xml);
			string image;
			string[] strFollowsIdArr;
			string[] strFollowsNameArr;
			string[] strFollowsImageArr;

            objNodes = xmldom.SelectNodes("/users/user");
			count = objNodes.Count;
			strFollowsIdArr = new string[objNodes.Count - 1 + 1];
			strFollowsNameArr = new string[objNodes.Count - 1 + 1];
			strFollowsImageArr = new string[objNodes.Count - 1 + 1];
			for (i = 0; i <= objNodes.Count - 1; i++)
			{
                node = objNodes.Item(i);
                id = node.SelectNodes("./id")[0].InnerText;
                name = node.SelectNodes("./name")[0].InnerText;
                image = node.SelectNodes("./profile_image_url")[0].InnerText;
				strFollowsIdArr[i] = id;
				strFollowsNameArr[i] = name;
				strFollowsImageArr[i] = image;
			}
			
			if (UpdateFriendFollowListCompleteEvent != null)
				UpdateFriendFollowListCompleteEvent(strFriendsIdArr, strFriendsArr, strFollowsIdArr, strFollowsNameArr, strFollowsImageArr, ErrorMsg);
			
		}
		
		//根据不同消息标志，装载消息列表
		public void UpdateMsgList_Renamed()
		{
            int i;
            string content;
            string image;
            string name;
            System.Xml.XmlNode node;
            string headline = "";
            string createdAt;
            string id;
            string userid;
            string username2 = "";
            DateTime dtCreatedAt;
            string strCreatedAt;
            string year;
            string month;
            string day;
            string time;
            TimeSpan tsTemp;
            string sHTML;
            string IDs;
            image = "";
            IDs = "";
            string[] ReplyMsgsIdArr2 = null;
            string[] ReplyMsgsNameArr2 = null;
            int[] ReplyMsgsFlagArr2 = null;
            string[] ReplyMsgsContentArr2 = null;


            if ((UserMsgFlg) == 1)
            {
                headline = "我做过什么…";
            }
            else if ((UserMsgFlg) == 2)
            {
                headline = "我和好友在做什么…";
            }
            else if ((UserMsgFlg) == 3)
            {
                headline = "好友给我的回复…";
            }
            else if ((UserMsgFlg) == 4)
            {
                headline = "我收到的私信…";
            }
            else if ((UserMsgFlg) == 5)
            {
                headline = "随便看看其他人在做什么…";
            }
            sHTML = "<html>";//font-weight: bolder;
            sHTML += "<head>";
            sHTML += "<script type=\"text/javascript\">";
            sHTML += "function  InvokeFunc(msg){alert(window.external.Reply(msg));  window.external.Reply();}";
            //sHTML += "window.external.ShowMessage(msg);}";
            sHTML += "</script>";
            sHTML += "<style type='text/css'>";

            sHTML += "* { margin:0; padding:0; font-family:宋体, Helvetica, sans-serif;}";
            sHTML += "html { overflow-y:scroll;}";
            sHTML += "body { background:#fff url(bg.gif) 0 0 repeat-x; font-size:16px; line-height:150%;}";

            sHTML += "a { color:#06c;}";
            sHTML += "a:hover { color:#ff7031;}";
            sHTML += "img { border:0; vertical-align:middle;}";

            sHTML += "#content { padding:10px 5px; border:1px solid #89d5ef; background:#fff;}";

            sHTML += "#stream h3 { padding:5px; color:#444; ffont-size:20px; border-bottom:1px solid #eee;}";
            sHTML += "#stream ol { list-style:none;}";
            sHTML += "#stream li {list-style:none; padding:10px 5px; border-bottom:1px solid #eee; font-size:16px; overflow:hidden; -o-text-overflow:ellipsis;}";
            sHTML += "#stream li.even { background:#eee;}";
            sHTML += "#stream li span.content { word-break:break-all;}";
            sHTML += "#stream li span.op a { font-size:16px; color:#999;}";
            sHTML += "#stream li span.op a:hover { color:red;}";
            sHTML += "#stream .wa li { padding:5px 5px 5px 62px;}";
            sHTML += "#stream .wa li:after { content:\".\"; display:block; font-size:0; line-height:0; clear:both; visibility:hidden;}";
            sHTML += "#stream .wa li.sys { padding:10px 5px 10px 5px;}";
            sHTML += "#stream .wa li { *zoom:1;}";
            sHTML += ".stamp { color:#999; margin-left:1em; font-size:16px;}";
            sHTML += ".stamp a { color:#999;}";

            sHTML += ".avatar { float:left; margin-left:-57px; padding:1px; border:1px solid #ccc; overflow:hidden;}";
            sHTML += ".avatar:hover { border:1px solid #ff7031;}";
            sHTML += ".avatar img { display:block; width:48px; height:48px;}";

            sHTML += "</style>";

            sHTML += "</head>";
            sHTML += "<body>";
            sHTML = sHTML + "<div id=\'content\'>";
            sHTML = sHTML + "<div id=\'stream\'>";
            sHTML = sHTML + "<h3>" + headline + "</h3>";
			string ErrorMsg;
			ErrorMsg = "";
			DateTime serverTime =DateTime.Now; //服务器时间，每次更新消息列表时使用
            try
            {
                string strxml = XMLMethod.sendRequest(Url, UseAuth, UserName, Password, ref serverTime, ref ErrorMsg).xml;
                System.Xml.XmlDocument xmldom = new System.Xml.XmlDocument();
                xmldom.LoadXml(strxml);
                System.Xml.XmlNodeList objNodes;
                if (UserMsgFlg == 4)
                {
                    objNodes = xmldom.SelectNodes("/private-messages/private_message");
                }
                else
                {
                    objNodes = xmldom.SelectNodes("/statuses/status");
                }



                //If (UserMsgFlg <> 1) Then
                sHTML = sHTML + "<ol class=\'wa\'>";
                //End If


                for (i = 0; i <= objNodes.Count - 1; i++)
                {
                    node = objNodes.Item(i);
                    if (i % 2 == 0)
                    {
                        sHTML = sHTML + "<li>";
                    }
                    else
                    {
                        sHTML = sHTML + "<li class=\'even\'>";
                    }

                    content = node.SelectNodes("text")[0].InnerText;//node.SelectNodes("text")[0].InnerText;


                    //这里可以直接显示图片、播放视频
                    //If (content.IndexOf(".gif") > 0 Or content.IndexOf(".jpg") > 0) Then
                    //    Dim beginPos = content.IndexOf("http")
                    //    Dim endPos = content.IndexOf(".gif")
                    //    If (endPos < 0) Then
                    //        endPos = content.IndexOf(".jpg")
                    //    End If
                    //    Dim imageUrl = Strings.Mid(content, beginPos + 1, endPos - beginPos + 4)
                    //    content = "<img src='" & imageUrl & "' /><br/>"
                    //End If

                    //content = System.Text.RegularExpressions.Regex.Replace(content, "/^http:\/\/www\.youtube\.com\/watch\?v=([\w-]+).*$/ig", _
                    //"<object width=""425"" height=""350""><param name=""movie"" value=""http://www.youtube.com/v/$1""></param><param name=""wmode"" value=""transparent""></param><embed src=""http://www.youtube.com/v/$1"" type=""application/x-shockwave-flash"" wmode=""transparent"" width=""425"" height=""350""></embed></object>")

                    content = System.Text.RegularExpressions.Regex.Replace(content, "(?<link>http://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?)", "<a onclick=\"window.external.DefaultLink(\'${link}\')\" href=\'javascript:void(0)\'>${link}</a>");

                    //If (content.IndexOf("http://") > -1) Then
                    //    Dim beginPos = content.IndexOf("http://")
                    //    Dim j As Integer
                    //    For j = beginPos To content.Length - 1
                    //        If (content.Chars(j) = Chr(32)) Then
                    //            Exit For
                    //        End If
                    //    Next j
                    //    Dim newUrl = Strings.Mid(content, beginPos + 1, j - beginPos)
                    //content = Strings.Left(content, beginPos) & "<a onclick=""window.external.DefaultLink('" & newUrl & "')"" href='javascript:void(0)'>" & newUrl & "</a>" & Strings.Right(content, content.Length - j)
                    //End If

                    createdAt = node.SelectNodes("created_at")[0].InnerText;
                    id = node.SelectNodes("id")[0].InnerText;
                    IDs = IDs + id;
                    year = createdAt.Substring(26, 4);
                    month = createdAt.Substring(4, 3);
                    day = createdAt.Substring(8, 2);
                    time = createdAt.Substring(11, 8);

                    dtCreatedAt = DateTime.Parse(day + "/" + month + "/" + year + " " + time);
                    dtCreatedAt = dtCreatedAt.AddHours(8);


                    tsTemp = DateTime.Now.Subtract(dtCreatedAt);


                    if (tsTemp.Hours < 24)
                    {
                        //24小时之内
                        if (tsTemp.Hours < 1)
                        {
                            //1小时之内
                            if (tsTemp.Minutes < 1)
                            {
                                //1分钟之内
                                strCreatedAt = tsTemp.Seconds + "秒前";
                            }
                            else
                            {
                                //大于小分钟小于1小时
                                strCreatedAt = tsTemp.Minutes + "分钟前";
                            }
                        }
                        else
                        {
                            //大于1小时小于24小时
                            strCreatedAt = "约" + tsTemp.Hours + "小时前";
                        }
                    }
                    else
                    {
                        //大于24小时
                        strCreatedAt = dtCreatedAt.Year + "-" + dtCreatedAt.Month + "-" + dtCreatedAt.Day + " " + dtCreatedAt.Hour + ":" + dtCreatedAt.Minute;
                    }
                    strCreatedAt = dtCreatedAt.ToString("yy-MM-dd HH:mm:ss");//DateTime.Parse(day + "/" + month + "/" + year + " " + time).ToString("yy-MM-dd HH:mm:ss");
                    if (UserMsgFlg == 4)
                    {
                        name = node.SelectNodes("sender_screen_name")[0].InnerText;
                        userid = node.SelectNodes("sender_id")[0].InnerText;

                        //匹配私信发送者图片
                        int j;
                        for (j = 0; j <= strFollowsIdArr.Length - 1; j++)
                        {
                            if (strFollowsIdArr[j] == userid)
                            {
                                image = strFollowsImageArr[j];
                                break;
                            }
                        }
                        if (image != "")
                        {
                            sHTML = sHTML + "<img src=\'" + image + "\' alt=\'" + name + "\' / class=\'avatar\'>  ";
                        }
                        image = "";


                        //sHTML = sHTML & "来自 " & name & "："
                        //ElseIf UserMsgFlg = 1 Then
                        //    userid = node.selectSingleNode("./user/id").Text
                    }
                    else
                    {
                        userid = node.SelectNodes("user/id")[0].InnerText;
                        username2 = node.SelectNodes("user/name")[0].InnerText;
                        image = node.SelectNodes("user/profile_image_url")[0].InnerText;
                        name = node.SelectNodes("user/name")[0].InnerText;
                        sHTML = sHTML + "<img src=\'" + image + "\' alt=\'" + name + "\' / class=\'avatar\'>  ";
                    }

                    if (UserMsgFlg == 2)
                    {
                        if (content.IndexOf("@" + UserName) > -1)
                        {
                            if (ReplyMsgsNameArr2 == null)
                            {
                                ReplyMsgsIdArr2 = new string[1];
                                ReplyMsgsNameArr2 = new string[1];
                                ReplyMsgsFlagArr2 = new int[1];
                                ReplyMsgsContentArr2 = new string[1];
                            }
                            else
                            {
                                Array.Resize(ref ReplyMsgsIdArr2, ReplyMsgsIdArr2.Length + 1);
                                Array.Resize(ref ReplyMsgsNameArr2, ReplyMsgsNameArr2.Length + 1);
                                Array.Resize(ref ReplyMsgsFlagArr2, ReplyMsgsFlagArr2.Length + 1);
                                Array.Resize(ref ReplyMsgsContentArr2, ReplyMsgsContentArr2.Length + 1);
                            }
                            ReplyMsgsIdArr2[ReplyMsgsIdArr2.Length - 1] = id;
                            ReplyMsgsNameArr2[ReplyMsgsNameArr2.Length - 1] = name;
                            ReplyMsgsFlagArr2[ReplyMsgsFlagArr2.Length - 1] = 0;
                            ReplyMsgsContentArr2[ReplyMsgsContentArr2.Length - 1] = content;
                        }
                    }

                    if (UserMsgFlg == 1)
                    {
                        sHTML = sHTML + "<span class=\'content\'>" + content + "</span>";
                    }
                    else
                    {
                        //sHTML = sHTML & "<span class='content'>" & name & ": " & content & "</span>"
                        sHTML = sHTML + "<span class=\'content\'>" + content + "</span>";
                    }
                    sHTML = sHTML + "<span class=\'stamp\'>" + strCreatedAt + "</span>";


                    if ((UserMsgFlg == 2) && (userid != UserName))
                    {
                        sHTML = sHTML + " <span class=\'op\'><a name='Reply' href=\"javascript:InvokeFunc(\'" + username2 + "\');\"" + "\' class=\'post_act\' title=\'回复\'>回复</a></span>";
                    }

                    if (UserMsgFlg != 4)
                    {
                        //TODO 收藏消息的api尚未公布
                        //sHTML = sHTML & " <span class='op'><a onclick=""window.external.AddFavorite('http://FanTong.com/favorites','action=favorite.add&favorite=" & id & "')"" href='javascript:void(0)'" & "' class='post_act' title='添加到我的收藏'>收藏</a>"
                        if (userid == UserName)
                        {
                            sHTML = sHTML + " <span class=\'op\'><a onclick=\"window.external.DeleteMsg(\'" + id + "\')\" href=\'javascript:void(0)\'" + "\' class=\'post_act\' title=\'删除\'>删除</a></span>";
                        }
                    }
                    else
                    {
                        sHTML = sHTML + " <span class=\'op\'><a onclick=\"window.external.ReplyPrivateMsg(\'" + userid + "\',\'" + name + "\')\" href=\'javascript:void(0)\'" + "\' class=\'post_act\' title=\'发私信\'>发私信</a></span>";
                        sHTML = sHTML + " <span class=\'op\'><a onclick=\"window.external.DeletePrivateMsg(\'" + id + "\')\" href=\'javascript:void(0)\'" + "\' class=\'post_act\' title=\'删除\'>删除</a></span>";
                    }

                    sHTML = sHTML + "</li>";
                }
                sHTML = sHTML + "</ol>";
            }
            catch (Exception e)
            {
                sHTML = sHTML + "<div><font>读取数据出错。</font></div>";
                ErrorMsg = "读取数据出错";
            }
			sHTML = sHTML + "</div></div>";
            sHTML += "</html>";
			
			if (UpdateMsgListCompleteEvent != null)
				UpdateMsgListCompleteEvent(sHTML, IDs, ReplyMsgsIdArr2, ReplyMsgsNameArr2, ReplyMsgsFlagArr2, ReplyMsgsContentArr2, ErrorMsg);
			
			
		}
		
	}
	
}
